import 'package:hinge/common/models/topic_comment_model.dart';
import 'package:hinge/common/services/user_service.dart';
import 'package:hinge/common/services/topic_service.dart';
import 'package:hinge/common/utils/sp_util.dart';
import 'dart:math' as math;

class TopicCommentService {
  static const String commentsStorageKey = 'app_topic_comments';

  static Future<void> initDemoComments() async {
    final comments = getAllComments();
    if (comments.isNotEmpty) {
      return;
    }

    await TopicService.initDefaultTopics();

    // Topic 1: Where do some perfume designs and inspirations come from?
    await _addDemoComment(
      1,
      1,
      "I've learned that many perfumes draw inspiration from 🌸 nature, especially floral and 🍊 fruit scents.",
    );
    await _addDemoComment(
      1,
      2,
      "Some perfumers find inspiration in ✨ memories and emotional experiences, like childhood recollections or special moments.",
    );
    await _addDemoComment(
      1,
      3,
      "🎨 Art and 🎵 music are important influences too - many fragrances are inspired by cultural expressions.",
    );
    await _addDemoComment(
      1,
      4,
      "Some brands derive inspiration from 📜 historical events or specific locations, like the naming of Chanel No. 5.",
    );
    await _addDemoComment(
      1,
      6,
      "I've noticed that many perfume designs draw inspiration from 📚 literature or 🎬 film scenes.",
    );
    await _addDemoComment(
      1,
      5,
      "Modern fragrances are also inspired by 🚀 technology and futurism, creating unprecedented scent profiles.",
    );

    // Topic 2: Any recommendations for fragrances that soothe your nerves?
    await _addDemoComment(
      2,
      2,
      "💜 Lavender essential oil is my top choice for calming nerves - gentle yet effective.",
    );
    await _addDemoComment(
      2,
      4,
      "I recommend perfumes with 🌿 chamomile notes, as they help relieve stress and anxiety.",
    );
    await _addDemoComment(
      2,
      7,
      "🍊 Bergamot and citrus scents have an energizing effect while also calming emotions.",
    );
    await _addDemoComment(
      2,
      1,
      "Jo Malone's 🍐 English Pear & Freesia gives me a sense of ✨ tranquility, perfect for bedtime use.",
    );

    // Topic 3: What happens to the smell of perfume when it expires?
    await _addDemoComment(
      3,
      1,
      "⏳ Expired perfumes typically lose their top notes, making the fragrance flat and lacking dimension.",
    );
    await _addDemoComment(
      3,
      3,
      "I've found that when perfumes expire, alcohol may evaporate, causing 🧪 chemical changes in concentration and strange odors.",
    );
    await _addDemoComment(
      3,
      5,
      "Some ingredients 🔄 oxidize and develop sour or vinegar-like notes, completely altering the original scent profile.",
    );

    // Topic 4: Which perfumes are worth collecting?
    await _addDemoComment(
      4,
      2,
      "💎 Limited edition releases from prestigious houses like Guerlain or Chanel are definitely worth collecting due to their rarity and historical significance.",
    );
    await _addDemoComment(
      4,
      3,
      "I recommend collecting 📚 discontinued classics that have shaped perfumery history, such as original formulations of Shalimar or 🏺 Mitsouko.",
    );
    await _addDemoComment(
      4,
      5,
      "✨ Niche perfumes with unique compositions and high-quality ingredients tend to hold their value, especially from houses like Frederic Malle or Serge Lutens.",
    );
    await _addDemoComment(
      4,
      6,
      "🕰️ Vintage perfumes from the 1980s and earlier often contain ingredients that are no longer available due to regulations, making them irreplaceable collectibles.",
    );
    await _addDemoComment(
      4,
      1,
      "🌟 Signature scents from famous perfumers like Jean-Claude Ellena or Francis Kurkdjian are worth collecting as they represent pivotal moments in fragrance development.",
    );

    // Topic 5: Who are some of the world-famous perfumers?
    await _addDemoComment(
      5,
      4,
      "🇫🇷 François Demachy, the nose behind many Dior fragrances, is renowned for his ✨ exceptional craftsmanship and ability to balance tradition with innovation.",
    );
    await _addDemoComment(
      5,
      3,
      "Christine Nagel, currently at Hermès, has created numerous 🌸 iconic scents including many for Jo Malone and Narciso Rodriguez before joining Hermès.",
    );
    await _addDemoComment(
      5,
      7,
      "👑 Francis Kurkdjian, founder of Maison Francis Kurkdjian, created the legendary Le Male for Jean Paul Gaultier at just 25 years old and is now artistic director at Dior Parfums.",
    );
    await _addDemoComment(
      5,
      2,
      "Olivier Cresp is the master perfumer behind many bestsellers including 🍬 Angel by Thierry Mugler, which pioneered the 🌠 gourmand category in perfumery.",
    );
    await _addDemoComment(
      5,
      5,
      "Jean-Claude Ellena, former in-house perfumer at Hermès, is famous for his 🌿 minimalist approach and 🧪 transparent compositions like Terre d'Hermès.",
    );
    await _addDemoComment(
      5,
      1,
      "💪 Sophia Grojsman created numerous bestsellers including 💄 Trésor for Lancôme and has been a pioneer for women in the perfume industry.",
    );
  }

  static List<TopicCommentModel> getAllComments() {
    return SpUtil.getModelList(
      commentsStorageKey,
      (json) => TopicCommentModel.fromJson(json),
    );
  }

  static Future<void> _addDemoComment(
    int topicId,
    int userId,
    String content,
  ) async {
    await addComment(
      topicId,
      userId,
      content,

      timestamp: DateTime.now().subtract(
        Duration(days: math.Random().nextInt(30) + 1),
      ),
    );
  }

  static List<TopicCommentModel> getCommentsByTopicId(int topicId) {
    return getAllComments()
        .where((comment) => comment.topicId == topicId)
        .toList();
  }

  static Future<TopicCommentModel> addComment(
    int topicId,
    int userId,
    String content, {
    DateTime? timestamp,
  }) async {
    final topic = TopicService.getTopicById(topicId);
    if (topic == null) {
      throw Exception('Topic with ID $topicId not found');
    }

    final user = UserService.getUserById(userId);
    if (user == null) {
      throw Exception('User with ID $userId not found');
    }

    final comments = getAllComments();

    int newId =
        comments.isEmpty ? 1 : comments.map((e) => e.id).reduce(math.max) + 1;

    final comment = TopicCommentModel(
      id: newId,
      topicId: topicId,
      userId: userId,
      user: user,
      timestamp: timestamp ?? DateTime.now(),
      content: content,
    );

    // Add to comment list
    comments.add(comment);

    // Save updated comment list
    await SpUtil.setModelList(
      commentsStorageKey,
      comments.map((comment) => comment.toJson()).toList(),
    );

    // Sync to topic service
    await _syncCommentToTopic(comment);

    return comment;
  }

  // Update comment
  static Future<bool> updateComment(int commentId, String newContent) async {
    final comments = getAllComments();
    int index = comments.indexWhere((comment) => comment.id == commentId);

    if (index != -1) {
      // Update comment content
      final updatedComment = comments[index].copyWith(content: newContent);
      comments[index] = updatedComment;

      // Save updated comment list
      await SpUtil.setModelList(
        commentsStorageKey,
        comments.map((comment) => comment.toJson()).toList(),
      );

      // Sync to topic service
      await _syncCommentToTopic(updatedComment);

      return true;
    }
    return false;
  }

  // Delete comment
  static Future<bool> deleteComment(int commentId) async {
    final comments = getAllComments();
    // Find the comment to delete
    int index = comments.indexWhere((comment) => comment.id == commentId);

    if (index != -1) {
      final commentToDelete = comments[index];

      // Remove from comment list
      comments.removeAt(index);

      // Save updated comment list
      await SpUtil.setModelList(
        commentsStorageKey,
        comments.map((comment) => comment.toJson()).toList(),
      );

      // Sync delete operation to topic service
      await _syncDeleteCommentFromTopic(commentToDelete.topicId, commentId);

      return true;
    }
    return false;
  }

  // Sync comment to topic service
  static Future<void> _syncCommentToTopic(TopicCommentModel comment) async {
    // Get topic
    final topic = TopicService.getTopicById(comment.topicId);
    if (topic == null) return;

    // Update comment list in topic
    final comments = List<TopicCommentModel>.from(topic.comments);

    // Check if this comment already exists
    int existingIndex = comments.indexWhere((c) => c.id == comment.id);
    bool isNewComment = existingIndex == -1;

    if (existingIndex != -1) {
      // Update existing comment
      comments[existingIndex] = comment;
    } else {
      // Add new comment
      comments.add(comment);

      // Each new comment increases topic percentage by 5%, not exceeding 100%
      double newPercentage = math.min(100.0, topic.percentage + 5.0);

      // Update topic (with new percentage)
      await TopicService.updateTopic(
        topic.copyWith(comments: comments, percentage: newPercentage),
      );
      return; // Topic already updated, return directly
    }

    // If only updating a comment without adding a new one, update topic without changing percentage
    await TopicService.updateTopic(topic.copyWith(comments: comments));
  }

  // Remove comment from topic
  static Future<void> _syncDeleteCommentFromTopic(
    int topicId,
    int commentId,
  ) async {
    // Get topic
    final topic = TopicService.getTopicById(topicId);
    if (topic == null) return;

    // Filter out the comment to delete
    final updatedComments =
        topic.comments.where((c) => c.id != commentId).toList();

    // Update topic
    await TopicService.updateTopic(topic.copyWith(comments: updatedComments));
  }
}
